package cn.catsdad.auth.service;

import cn.catsdad.auth.context.AuthenticationContextHolder;
import cn.catsdad.dto.DepartmentDTO;
import cn.catsdad.dto.UserDTO;
import cn.catsdad.service.api.DepartmentService;
import cn.catsdad.service.api.MenuService;
import cn.catsdad.service.api.UserService;
import cn.catsdad.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * 实现spring security的用户详情
 *
 * @author xuyonglong
 * @version V1.0 2023/4/10
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private UserService userService;
    private DepartmentService departmentService;
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        UserDTO user = userService.queryUserByLoginName(username);
        Authentication authentication = AuthenticationContextHolder.getContext();
        userService.loginPasswordValidate(user, authentication.getCredentials().toString());
        return createLoginUser(user);
    }

    /**
     * 创建登录用户
     *
     * @param uer 项目实际用户对象
     * @return 登录用户
     */
    private LoginUser createLoginUser(UserDTO uer) {
        LoginUser result = new LoginUser(uer);
        //填充部门信息
        DepartmentDTO DepartmentDTO = departmentService.queryDepartmentOfUser(uer.getId());
        if (DepartmentDTO != null) {
            result.setDepartmentId(DepartmentDTO.getId());
            result.setDepartmentName(DepartmentDTO.getName());
        }
        //填充当前用户具备的功能项权限
        result.setMenuList(menuService.queryMenuOfUser(uer.getId()));
        return result;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setDepartmentService(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    @Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }
}
